let websocket = null;

//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    //连接WebSocket节点
    websocket = new WebSocket("ws://localhost:41110/websocket/txt/");
} else {
    setMessageInnerHTML(`<p class="sys">当前浏览器不支持WebSocket</p>`)
}
//连接发生错误的回调方法
websocket.onerror = function () {
    setMessageInnerHTML(`<p class="sys">连接失败</p>`);
};
//连接成功建立的回调方法
websocket.onopen = function () {
    setMessageInnerHTML(`<p class="sys">连接成功</p>`);
}
//接收到消息(类型为MessageEvent)的回调方法
websocket.onmessage = function (event) {
    setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
    setMessageInnerHTML(`<p class="sys">连接已关闭</p>`);
}
//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接
window.onbeforeunload = function () {
    websocket.close();
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
    document.getElementById('message').innerHTML += innerHTML;
}

//定时移除元素
function removeElementTimely(ele, ms = 1000) {
    setTimeout(function () {
        document.body.removeChild(ele)
    }, ms);
}

//创建通知框
function createNotifyBox(content = '无提示内容') {
    let div = document.createElement('div');
    div.classList.add('notify')
    div.innerHTML = `<h3>温馨提示</h3>${content}`;
    document.body.appendChild(div)
    return div;
}

//发送消息
function sendMessage() {
    const content = document.getElementById('text').value
    //提示
    if (websocket.readyState === WebSocket.CLOSED) {
        const div = createNotifyBox('连接已关闭，无法通信，请重连');
        removeElementTimely(div, 3000)
        return;
    }
    if (content === null || content === '') {
        const div = createNotifyBox('请输入内容');
        removeElementTimely(div, 1500);
        return;
    }
    const dateTime = new Date().toLocaleString();
    const message = `<div class="msg"><span class="txt">${dateTime}:</span>${content}</div>`;
    websocket.send(message);
}

//清空输入框
function clearInput() {
    document.getElementById('text').value = ''
}

//清屏
function cleanScreen() {
    document.getElementById('message').innerHTML = ''
}

//关闭连接
function closeWebSocket() {
    websocket.close();
}

//重新连接
function reConnect() {
    location.reload();
}